<?php
/**
 * Created by xuan.
 * Author: xuan
 * Date: 2018/8/3
 * Time: 18:24
 */

namespace app\api\controller\v1;
use app\api\model\Admin as AdminModel;
use think\Request;
use think\Session;
use app\api\controller\BaseController;
use web\util\WebUtil;
use app\api\service\WithdrawService;
use app\api\model\Member as MemberModel;

class Admin  extends BaseController
{
    private $adminModel = null;
    function __construct(){
        parent::__construct();
        //$this->adminModel = new Admin();
    }
	
    /**
     * 添加管理员
     *
     *
     */
    public function add()
    {
        
		if (request()->isPost()){
			$all = Request::instance()->param();
			if(empty($all['username'])){
				return json(["returnCode"=>-6,"returnMsg"=>"必填参数不能为空!"]);exit;
			}elseif(empty($all['password'])){
				return json(["returnCode"=>-6,"returnMsg"=>"必填参数不能为空!"]);exit;
			}
			$all['password']=md5($all['password']);
			$dataByName = AdminModel::selectOneAdminByName($all['username']);
			if($dataByName){
				return json(["returnCode"=>-3,"returnMsg"=>"该用户名已占用!","data"=>""]);
			}else{
				$data = AdminModel::addOneAdmin($all);
				if($data){
					return json(["returnCode"=>1,"returnMsg"=>"success!","data"=>""]);
				}else{
					return json(["returnCode"=>-2,"returnMsg"=>"fail!","data"=>""]);
				}
			}
		}else{
			return json(["returnCode"=>-6,"returnMsg"=>"参数不能为空!","data"=>""]);
			
		}
		
		
    }
	
	public function login(){
		if (request()->isPost()){
			$all = Request::instance()->param();
			if(empty($all['username'])){
				return json(["returnCode"=>-6,"returnMsg"=>"post必填参数不能为空!","data"=>""]);exit;
			}elseif(empty($all['password'])){
				return json(["returnCode"=>-6,"returnMsg"=>"post必填参数不能为空!","data"=>""]);exit;
			}
			
			if (! captcha_check($all['verify_code'])) {
			    return $this->returnResult(-1,'验证码错误');
			}
			
			$dataByName = AdminModel::selectOneAdminByName($all['username']);
			
			if($dataByName){
				$dataByName = $dataByName->toArray();
				if($dataByName['password'] == md5($all['password'])){
					if($dataByName['isshow']==2){
						return json(["returnCode"=>-5,"returnMsg"=>"账号审核中!","data"=>""]);
					}else{
						Session::set('ADMIN_KEY',$dataByName['id']);
						return json(["returnCode"=>1,"returnMsg"=>"success!"]);
					}
				}else{
					return json(["returnCode"=>-4,"returnMsg"=>"账号密码错误!","data"=>""]);
				}
			}else{
				return json(["returnCode"=>-3,"returnMsg"=>"账号不存在!","data"=>""]);
			}
		}else{
			return json(["returnCode"=>-6,"returnMsg"=>"post参数不能为空!","data"=>""]);	
		}
		
	}
	
	/**
     * 列表
     */
    public function lists()
    {
		
		if (request()->isPost()){
			$length = 10;
			$all = Request::instance()->param();
			if(empty($all['start'])){ $start = 0; }else{ $start = trim($all['start']); }
			if(empty($all['draw'])){ $draw = 1; }else{ $draw = trim($all['draw']); }
			if(empty($all['title'])){ $title = ''; }else{ $title = trim($all['title']); }
			if(empty($all['grade'])){ $grade = 0; }else{ $grade = trim($all['grade']); }
			if(empty($all['status'])){ $status = 0; }else{ $status = trim($all['status']); }
			
			$where = ' 1 = 1 ';
			if ($title) {
				$where .= ' AND name LIKE "%' . $title . '%" ';
				$where .= ' AND tel LIKE "%' . $title . '%" ';
				$where .= ' AND weixin LIKE "%' . $title . '%" ';
			}

			if ($grade) {
				$where .= ' AND grade = ' . $grade . ' ';
			}
			
			if ($status) {
				$where .= ' AND status = ' . $status . ' ';
			}
			
			$list = MemberModel::getListByWhere($where, $start, $length);
			$count = MemberModel::getCount($where);
			
			$data2 = MemberModel::MemberLists();
			$count2 = count($data2);
			$data = array("returnCode"=>1,"returnMsg"=>"success!", 'recordsTotal' => $count2, 'recordsFiltered' => $count, 'draw' => $draw,'data' => $list);
			return json($data);
		}else{
			return json(["returnCode"=>-2,"returnMsg"=>"fail!","data"=>""]);
		}
    }
	
	
	/**查询一条记录*/
	public function find(){
		$all = Request::instance()->param();
		$data = MemberModel::selectOneMemberByID($all['id']);
		if($data){
			return json(["returnCode"=>1,"returnMsg"=>"success!","data"=>$data]);
		}else{
			return json(["returnCode"=>-2,"returnMsg"=>"fail!"]);
		}
	}
	

	/**退出登录*/
	public function outlogin(){
		Session::set('USER_KEY',null);
		//Session::set('USER_TIME',null);
		//Session::set('USER_USERNAME',null);
		
		return json(["returnCode"=>1,"returnMsg"=>"success!"]);
	}
	
	/**
	 * 充值
	 */
	public function  recharge(){
	    
	   $mid =$this->getLoginId();
	    if(empty($mid)){
            return $this->returnResult(-7,'请登录!');
	    }
	    $money = $this->request->param('money',0,'float');
	    $pic = $this->request->param("pic",'');
	    if($money <=0 || empty($pic)){
	        return $this->returnResult(-1,'参数错误');
	    }
	   $data = [
	        'mid'=>$mid,
	        'type'=>1,
	        'money'=>$money,
	        'ifpass'=>0,
	        'cash_name'=>'充值',
	        'addtime'=> date('Y-m-d/ h:i:s',time()),
	        'pic'=>$pic,
	    ];
	    $id = $this->rechargeModel->insert($data);
	    if($id){
	        return $this->returnResult(1);
	    }else{
	        return $this->returnResult(0,'充值失败');
	    }
	}
	
	public function recharge_list(){
	    $mid = $this->getLoginId();
	    if(empty($mid)){
	       return $this->returnResult(-7,'请登录!');
	    }
	    $draw= $this->request->param('draw','1','intval');
	    $count = $this->rechargeModel->getRechargeListCount($mid);
	    $items = $this->rechargeModel->getRechargeList($mid);
	    $list= [];
	    $memberMap = [];
	    foreach ($items as $item){
	        $member = null;
	        $smid = $item['mid'];
	        if(array_key_exists($smid, $memberMap)){
	            $member = $memberMap[$smid];
	        }else{
	            $member = MemberModel::selectOneMemberByID($smid);
	            $memberMap[$smid] = $member;
	        }
	        $temp = [
	            'id'=>$item['id'],
	            'nickname'=>$member['name'],
	            'avatar'=>$member['face'], 
	            'money'=>$item['money'],
	            'type_name'=>'充值',
	            'status'=>$item['ifpass'],
	            'status_name'=>$this->_getStatusName($item['ifpass']),
	            'ctime'=>date('Y/m/d',strtotime($item['addtime'])),
	        ];
	        $list[] = $temp;
	    }
	    $data = array("returnCode"=>1,"returnMsg"=>"success!", 'recordsTotal' => $count, 'recordsFiltered' => $count, 'draw' => $draw,'data' => $list);
	    return json($data);
	}
	
	/**
	 * 充值
	 */
	public function  recharge_detail(){
	    $mid =$this->getLoginId();
	    if(empty($mid)){
	           return $this->returnResult(-7,'请登录!');
	    }
	    $id= $this->request->param('id','0','intval');
	    if(empty($id)){
	        return $this->returnResult(-1,'参数错误');
	    }
	    $item = $this->rechargeModel->getById($mid,$id);
	    if(empty($item)){
	        return $this->returnResult(-1,'参数错误');
	    }
	    
	    $member = MemberModel::selectOneMemberByID($mid);
	    $data = [
	         'id'=>$item['id'],
	        'nickname'=>$member['name'],
	        'avatar'=>$member['face'], 
	        'money'=>$item['money'],
	        'type_name'=>'充值',
	        'reviewer'=>'总部',
	        'status'=>$item['ifpass'],
	        'status_name'=>$this->_getStatusName($item['ifpass']),
	        'ctime'=>date('Y/m/d',strtotime($item['addtime'])),
	    ];
	    return $this->returnResult(1,'',$data);
	}
	
	/**
	 * 提现
	 */
	public function withdraw(){
        $mid =$this->getLoginId();
    	if(empty($mid)){
    	   return $this->returnResult(-7,'请登录!');
    	}
	    $money = $this->request->param('money',0,'floatval');
	    $all = $this->request->param('all',0,'intval');
	    $bankId = $this->request->param("bank_id",'0','intval');
	    if(!($money > 0 || $all) || empty($bankId)){
	        return $this->returnResult(-1,'参数错误');
	    }
	    $result = WithdrawService::withdraw($mid, $money, $all, $bankId);
	    list($res,$msg) = $result;
	    if($res){
	        return $this->returnResult(1);
	    }else{
	        return $this->returnResult(0,$msg);
	    }
	}
	
	/**
	 * 提现列表
	 */
	public function withdraw_list(){
	    $mid =$this->getLoginId();
	    if(empty($mid)){
	        return $this->returnResult(-7,'请登录!');
	    }
	    $draw= $this->request->param('draw','1','intval');
	    if(empty($draw) || $draw <= 0){
	        $draw =1;
	    }
	    $count= $this->rechargeModel->getWithdrawListCount($mid);
	    $items = $this->rechargeModel->getWithdrawList($mid,$draw);
	    $list = [];
	    $memberMap = [];
	    foreach ($items as $item){
	        $member = '';
	        $smid = $item['mid'];
	        if(array_key_exists($smid, $memberMap)){
	            $member = $memberMap[$smid];
	        }else{
	            $member = MemberModel::selectOneMemberByID($smid);
	            $memberMap[$smid] = $member;
	        }
	        $temp = [
	            'id'=>$item['id'],
	            'nickname'=>$member['name'],
	            'avatar'=>$member['face'],
	            'money'=>$item['money'],
	            'type_name'=>'提现',
	            'status'=>$item['ifpass'],
	            'status_name'=>$this->_getStatusName($item['ifpass']),
	            'ctime'=>date('Y/m/d',strtotime($item['addtime'])),
	        ];
	        $list[] = $temp;
	    }
	    
	    $data = array("returnCode"=>1,"returnMsg"=>"success!", 'recordsTotal' => $count, 'recordsFiltered' => $count, 'draw' => $draw,'data' => $list);
	    return json($data);
	   
	}
	
	/**
	 * 提现详情
	 */
	public function withdraw_detail(){
	    $mid =$this->getLoginId();
	    if(empty($mid)){
            return $this->returnResult(-7,'请登录!');
	    }
	    $id= $this->request->param('id','0','intval');
	    if(empty($id)){
	        return $this->returnResult(-1,'参数错误');
	    }
	    $item = $this->rechargeModel->getById($mid,$id);
	    if(empty($item)){
	        return $this->returnResult(-1,'参数错误');
	    }
	    
	    $member = MemberModel::selectOneMemberByID($mid);
	    $bank = Payment::selectOnePaymentByID($item['bank_id']);
	    $data = [
	        'id'=>$item['id'],
	        'nickname'=>$member['name'],
	        'avatar'=>$member['face'], 
	        'money'=>$item['money'],
	        'type_name'=>'提现',
	        'reviewer'=>'总部',
	        'status'=>$item['ifpass'],
	        'status_name'=>$this->_getStatusName($item['ifpass']),
	        'ctime'=>date('Y/m/d',strtotime($item['addtime'])),
	        'bank'=>[
	            'paytype_name'=>$this->_getPaymentTypeName($bank['paytype']),
	            'name'=>$bank['name'],
	            'addr'=>$bank['addr'],
	            'num'=>$bank['num'],
	        ]
	    ];
	    return $this->returnResult(1,'',$data);
	}
	
	private function _getStatusName($status){
	    return WebUtil::getStatusName($status);
	}
	
	private function _getPaymentTypeName($paytype){
	   return WebUtil::getPaymentTypeName($paytype);
	}
	
	/**后台代理审核*/
	public function shenhe(){
		$all = Request::instance()->param();
		$data = MemberModel::shenhe($all);
		if($data){
			return json(["returnCode"=>1,"returnMsg"=>"success!"]);
		}else{
			return json(["returnCode"=>-2,"returnMsg"=>"fail!"]);
		}
	}
}